<template>
  <view class="project-setting">
    <view class="tab-box">
      <view
          v-for="item in tabList"
          :key="item.code"
          class="tab-item"
          :class="{ active: activeTab === item.code, disabled: item.disabled }"
          @click="toggleTab(item)">
        <view class="icon">
          <text class="iconfont" :class="item.icon"></text>
        </view>
        <view class="label">{{ item.name }}</view>
      </view>
    </view>
    <div class="content-box">
      <base-setting v-show="activeTab === SETTING_TYPE.BASE" ref="base" :project-info="projectInfo" :param-list="paramList" :scene-map="sceneMap" :scene-list="sceneList" />
      <group-setting v-show="activeTab === SETTING_TYPE.GROUP" ref="group" :project-info="projectInfo" />
      <area-setting v-show="activeTab === SETTING_TYPE.AREA" ref="area" :project-info="projectInfo" />
      <scenario-setting v-show="activeTab === SETTING_TYPE.SCENARIO" ref="scene" :project-info="projectInfo" :scene-list="sceneBaseList" @refreshScene="getProjectScene" />
      <time-setting v-show="activeTab === SETTING_TYPE.TIME" ref="time" :project-info="projectInfo" :scene-time-list="sceneTimeList" @refreshScene="getProjectScene" />
    </div>
  </view>
</template>

<script>
import mixin from '@/mixins/index.js'
import { USER_ROLE } from '@/constant/index.js'
import { getGUID, formatDate } from '@/utils/index.js'
import BaseSetting from "./components/base-setting";
import GroupSetting from "./components/group-setting";
import AreaSetting from "./components/area-setting";
import ScenarioSetting from "./components/scenario-setting";
import TimeSetting from "./components/time-setting";
const SETTING_TYPE = {
  BASE: 'base',
  GROUP: 'group',
  AREA: 'area',
  SCENARIO: 'scene',
  TIME: 'time'
}

export default {
  mixins: [mixin],
  components: {
    BaseSetting,
    GroupSetting,
    AreaSetting,
    ScenarioSetting,
    TimeSetting
  },
  data() {
    return {
      SETTING_TYPE,
      activeTab: SETTING_TYPE.BASE,
      tabList: [
        { code: SETTING_TYPE.BASE, name: '基础', icon: 'icon-base-setting' },
        { code: SETTING_TYPE.GROUP, name: '分组', icon: 'icon-group-setting' },
        { code: SETTING_TYPE.AREA, name: '区域', icon: 'icon-area-control' },
        { code: SETTING_TYPE.SCENARIO, name: '场景', icon: 'icon-lamp' },
        { code: SETTING_TYPE.TIME, name: '时控', icon: 'icon-time-control' }
      ],
      projectInfo: {},
      paramList: [],
      paramMap: {},
      sceneList: [],
      sceneBaseList: [],
      sceneTimeList: [],
      sceneMap: {}
    }
  },
  mounted() {
    this.getProjectInfo(true)
  },
  onShow() {
    this.refreshChildPage()
  },
  onPullDownRefresh() {
    this.refreshChildPage()
  },
  methods: {
    getProjectInfo(refresh) {
      const self = this
      uni.request({
        url: '/project/get',
        data: {
          id: self.params.id
        },
        success(result) {
          if (result.data.success && result.data.data) {
            const projectInfo = result.data.data
            const userInProject = projectInfo.members?.find((user) => user.user_id === self.userInfo.id)
            projectInfo.name = projectInfo.name || ''
            projectInfo.online = !!projectInfo.online
            projectInfo.isOwner = projectInfo.user_id === self.userInfo?.id
            projectInfo.canEdit = projectInfo.isOwner || [0, 1].includes(userInProject.role) || self.canEdit
            projectInfo.sceneName = projectInfo.sceneName || '';
            projectInfo.sceneType = projectInfo.sceneType || '';
            projectInfo.params = {};
            if (projectInfo._param) {
              try {
                projectInfo.params = JSON.parse(projectInfo._param);
              } catch (e) {
                console.error(e);
              }
            }
            self.projectInfo = projectInfo
            uni.setNavigationBarTitle({
              title: projectInfo.name
            })
            self.getParamList()
            if (refresh) {
              setTimeout(self.refreshChildPage, 1)
            }
          }
        }
      })
    },
    getParamList() {
      const self = this
      self.paramMap = {}
      self.paramList = []
      uni.request({
        url: '/sys/fieldsn',
        method: 'GET',
        success(result) {
          if (result.data.success && Array.isArray(result.data.data)) {
            const arr = []
            result.data.data.forEach((item) => {
              if (!item) return
              const { label = '', name, value, type, step = 1, min = 0, max = 100, desc, range = [], user = 1 } = item
              range.forEach((option) => {
                option.text = option.name || ''
              })
              const paramItem = {
                key: getGUID(),
                label,
                name,
                value,
                type,
                step,
                min,
                max,
                desc,
                range,
                hidden: user === 1 ? false : self.userInfo.role !== USER_ROLE.ADMIN,
                nameMap: {},
              }
              paramItem.range.forEach((option) => {
                option.text = option.name || '';
                paramItem.nameMap[option.value] = option.name;
              });
              self.paramMap[name] = paramItem;
              arr.push(paramItem)
            })
            self.paramList = arr
            self.getProjectScene()
          }
        }
      })
    },
    getProjectScene() {
      const self = this
      self.sceneList = []
      uni.request({
        url: '/project_scene/list',
        data: {
          xm_id: this.projectInfo.id
        },
        success(result) {
          if (result.data.success && Array.isArray(result.data.data)) {
            const allScene = [];
            const baseScene = [];
            const timeScene = [];
            result.data.data.forEach(item => {
              const sceneItem = {
                key: item.id,
                id: item.id,
                name: item.name || '',
                text: item.name || '',
                value: item.id,
                type: item.type,
                modifyTime: formatDate(item.modify_time, 'yyyy.MM.dd'),
                displayParams: [],
                params: {},
                scene: item.scene,
                scene_type: item.scene_type,
                weekdays: item.weekdays,
                date_start: item.date_start,
                date_end: item.date_end,
                isTimeScene: false,
              }
              if (item.param) {
                try {
                  const itemParam = JSON.parse(item.param)
                  sceneItem.params = itemParam
                  const displayArr = ['model', 'close_light', 'open_light', 'delay'];
                  sceneItem.displayParams = Array.from(
                      Object.keys(itemParam)
                          .filter(child => displayArr.includes(child) && self.paramMap[child]),
                      (key) => {
                        const valueText = self.paramMap[key].nameMap?.[itemParam[key]] ?? itemParam[key]
                        return { label: self.paramMap[key].label, value: valueText }
                      }
                  )
                } catch (e) {
                  console.error(e)
                }
              }
              if (item.scene_type === 0) {
                baseScene.push(sceneItem);
              } else {
                sceneItem.isTimeScene = true;
                const cases = {
                  1: '每天重复',
                  2: '每周重复',
                  3: '指定日期',
                };
                sceneItem.sceneTypeText = cases[item.scene_type];
                timeScene.push(sceneItem);
              }
              self.sceneMap[sceneItem.id] = sceneItem
              allScene.push(sceneItem)
            })
            if (self.projectInfo.scene) {
              const target = self.sceneMap[self.projectInfo.scene];
              self.projectInfo.sceneName = target?.name;
              self.projectInfo.sceneType = target?.type;
            }
            self.sceneList = allScene
            self.sceneBaseList = baseScene
            self.sceneTimeList = timeScene
          }
        },
        complete() {
          uni.stopPullDownRefresh()
        }
      })
    },
    refreshChildPage() {
      const self = this
      self.getProjectInfo()
      const cases = {
        [SETTING_TYPE.BASE]: self.$refs.base,
        [SETTING_TYPE.GROUP]: self.$refs.group,
        [SETTING_TYPE.AREA]: self.$refs.area,
        [SETTING_TYPE.SCENARIO]: self.$refs.scene,
        [SETTING_TYPE.TIME]: self.$refs.time,
      }
      cases[self.activeTab].initData()
    },
    toggleTab(tab) {
      const self = this
      if (tab.disabled) return
      self.activeTab = tab.code
      self.refreshChildPage()
    }
  }
}
</script>

<style lang="scss" scoped>
.project-setting {

}
.tab-box {
  background-color: $white;
  padding: 15rpx 30rpx;
  display: flex;
  justify-content: space-between;
  .tab-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 125rpx;
    height: 125rpx;
    border-radius: 10rpx;
    border: 2rpx solid $background-base;
    background-color: $background-base;
    .icon {
      font-size: 40rpx;
    }
    .label {
      font-size: 28rpx;
    }
    &.disabled {
      color: $text-extra;
      border-color: $background-light;
      background-color: $background-light;
    }
    &.active {
      color: $primary;
      border-color: $primary;
      background-color: rgba($primary, .1);
    }
  }
}
.content-box {
  padding: 30rpx;
}
</style>
